package cn.maxxieyi.aichatbot.controller;

import cn.maxxieyi.aichatbot.holder.ItchatHolder;
import cn.maxxieyi.aichatbot.vo.BasicResultVO;
import cn.zhouyafeng.itchat4j.api.WechatTools;
import cn.zhouyafeng.itchat4j.core.Core;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * 机器人接口
 */
@RestController
@RequestMapping("/aichat")
@Slf4j
public class AiChatBotController {

    @Autowired
    private ItchatHolder itchatHolder;


    /**
     * 登录微信
     *
     * @return
     */

    @RequestMapping(path = "/wxlogin", method = RequestMethod.GET)
    public BasicResultVO wxlogin(HttpServletResponse response) {

        if (Core.getInstance().isAlive()) {
            JSONObject resp = new JSONObject();
            resp.put("nickName", Core.getInstance().getNickName());
            resp.put("login", true);
            return BasicResultVO.success(resp);
        }
        itchatHolder.getWechat().getLogin().refreshQrCode();
        String path = itchatHolder.getChatBotConfig().getQrPath() + "/QR.jpg";
        try (OutputStream os = response.getOutputStream();
             InputStream is = new FileInputStream(path)) {
            String contentType = "image/jpeg";
            BufferedImage image = ImageIO.read(is);
            response.setContentType(contentType);
//            os = response.getOutputStream();
            if (image != null) {
                ImageIO.write(image, "jpg", os);
            }
        } catch (IOException e) {
            log.error("图片输出失败", e);
        }
        return null;
    }

    @RequestMapping(path = "/wxlogout", method = RequestMethod.POST)
    public BasicResultVO wxlogout() {
        WechatTools.logout();
        return BasicResultVO.success();
    }

}
